<!--
 * @Description: 计划详情
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-12-01 16:56:43
 * @LastEditTime: 2023-05-24 17:23:32
 * @FilePath: \cscec-pms-admin\src\views\construction\constructionSchedule\planDetails.vue
-->
<template>
  <base-breadcrumb :title="breadcrumb">
    <a-card>
      <title-name :title="breadcrumbText[mode]+'计划列表'" />
      <div class="btn-wrapper">
        <template v-if="!isDetail">
          <a-button
            type="primary"
            :disabled="notSelectRow || isDetail || selectRow.nodeType === 0 || selectRow.isMonthWeekCreated!== true"
            @click="handleRemove"
          >
            删除节点
          </a-button>
          <a-button
            type="primary"
            :disabled="notSelectRow || isDetail || selectRow.nodeType === 0"
            @click="handlePrepose"
          >
            前移一天
          </a-button>
          <a-button
            type="primary"
            :disabled="notSelectRow || isDetail || selectRow.nodeType === 0"
            @click="handleCreateWork"
          >
            新增同级节点
          </a-button>
        </template>
        <a-button
          type="primary"
          :disabled="loading"
          @click="allTreeExpansion"
        >
          展开全部
        </a-button>
        <a-button
          type="primary"
          :disabled="loading"
          @click="$refs.table.clearTreeExpand()"
        >
          收起全部
        </a-button>
      </div>
      <div class="pub-table-select-count">
        <a-icon
          type="info-circle"
          theme="twoTone"
        />
        <span>
          项目名称：<span class="totalNum">{{ total.projectName }}</span> |
        </span>
        <span>
          当前进行{{ breadcrumbText[mode] }}计划：<span class="totalNum">{{ total.currentProceedPlan }}</span> |
        </span>
        <span>
          本{{ breadcrumbText[mode] }}需进行节点总数：<span
            :class="{'totalNum':true,'plan-list-filter':isDetail}"
            @click="handlePlanListFilter(`本${ breadcrumbText[mode] }需进行节点`,`current${getCapitalize(mode)}Node`)"
          >{{ total.currentProceedNodeNum }}</span> 个 |
        </span>
        <span>
          本{{ breadcrumbText[mode] }}计划开始节点数：<span
            :class="{'totalNum':true,'plan-list-filter':isDetail}"
            @click="handlePlanListFilter(`本${ breadcrumbText[mode] }计划开始节点`,`current${getCapitalize(mode)}StartNode`)"
          >{{ total.currentPlanStartNodeNum }}</span> 个 |
        </span>
        <span>
          本{{ breadcrumbText[mode] }}计划结束节点数：<span
            :class="{'totalNum':true,'plan-list-filter':isDetail}"
            @click="handlePlanListFilter(`本${ breadcrumbText[mode] }计划结束节点`,`current${getCapitalize(mode)}EndNode`)"
          >{{ total.currentPlanEndNodeNum }}</span> 个 |
        </span>
        <span>
          延期到本{{ breadcrumbText[mode] }}节点数：<span
            :class="{'totalNum':true,'plan-list-filter':isDetail}"
            @click="handlePlanListFilter(`延期到本${ breadcrumbText[mode] }节点`,`current${getCapitalize(mode)}DelayNode`)"
          >{{ total.delayCurrentNodeNum }}</span> 个
        </span>
      </div>
      <a-spin :spinning="loading">
        <u-table
          ref="table"
          fixed-columns-roll
          :height="500"
          show-header-overflow
          :tree-config="{
            children: 'childTree',
            expandAll: false,
          }"
          row-id="id"
          :use-virtual="true"
          border
          class="construction-schedule-view-table"
          @row-click="handleRowClick"
        >
          <u-table-column
            v-for="item in columns8"
            :key="item.dataIndex"
            :prop="item.dataIndex"
            :label="item.title"
            :width="item.width"
            :tree-node="item.dataIndex === 'phaseCategory'"
            align="center"
          >
            <template v-slot="{ row }">
              <!-- 查看 -->
              <span
                v-if="isDetail"
                :title="row[item.dataIndex]"
                class="span-ellipsis"
              >
                <template v-if="row.nodeType === 0">
                  <template v-if="['sortNum','phaseCategory','businessMatters','period','planStartTime','planEndTime'].includes(item.dataIndex)">
                    {{ row[item.dataIndex] }}
                  </template>
                </template>
                <template v-else>
                  <template v-if="item.dataIndex === 'controlLevelId'">
                    {{ row.controlLevelName }}
                  </template>
                  <template v-else-if="item.dataIndex === 'directResPerList'">
                    {{ row[item.dataIndex].map(el=>el.label).join(',') }}
                  </template>
                  <a-switch
                    v-else-if="['isKeyNode','isMilestonesNode','isMainProcessNode','isVerticalTransportNode'].includes(item.dataIndex)"
                    v-model="row[item.dataIndex]"
                    checked-children="是"
                    un-checked-children="否"
                    disabled
                  />
                  <template v-else>
                    {{ row[item.dataIndex] }}
                  </template>
                </template>
              </span>
              <!-- 查看 -->
              <!-- 编辑 -->
              <span
                v-else
                :title="row[item.dataIndex]"
              >
                <!-- 阶段类别 -->
                <span
                  v-if="row.nodeType === 0"
                  class="span-ellipsis"
                >
                  <span v-if="['sortNum','phaseCategory','businessMatters','period','planStartTime','planEndTime'].includes(item.dataIndex)">
                    {{ row[item.dataIndex] }}
                  </span>
                </span>
                <!-- 阶段类别 -->
                <!-- 业务事项 -->
                <template v-else>
                  <!-- 序号 -->
                  <span
                    v-if="item.dataIndex === 'sortNum'"
                    :class="'class-'+row.statusLights"
                    class="sort-num"
                  >
                    <img
                      v-if="row.promptLights === 1 || row.promptLights === 2"
                      :src="row.promptLights === 1 ? yellowLight : redLight"
                      width="20"
                      hight="20"
                    >
                    <span>{{ row[item.dataIndex] }}</span>
                  </span>
                  <!-- 序号 -->
                  <template v-else-if="row.isMonthWeekCreated === true">
                    <!-- 业务事项 -->
                    <BaseInput
                      v-if="item.dataIndex === 'businessMatters'"
                      v-model="row.businessMatters"
                      :placeholder="'请输入'+item.title"
                      @blur="handleUpdate(row)"
                    />
                    <!-- 业务事项 -->
                    <!-- 管控级别 -->
                    <a-select
                      v-if="item.dataIndex === 'controlLevelId'"
                      v-model="row.controlLevelId"
                      :placeholder="'请选择'+item.title"
                      class="width-100"
                      @change="handleUpdate(row,true)"
                    >
                      <a-select-option
                        v-for="{value,label} in controlLevelList"
                        :key="value"
                        :value="value"
                      >
                        {{ label }}
                      </a-select-option>
                    </a-select>
                    <!-- 管控级别 -->
                    <!-- 周期(天) -->
                    <BaseInputNumber
                      v-if="item.dataIndex === 'period'"
                      v-model="row.period"
                      :placeholder="'请输入'+item.title"
                      :min="1"
                      :max="2000"
                      :is-int="true"
                      @blur="(e)=>{handleComputePeriod(e.target._value,row,0)}"
                    />
                    <!-- 周期(天) -->
                    <!-- 计划开始时间 -->
                    <a-date-picker
                      v-if="item.dataIndex === 'planStartTime'"
                      v-model="row.planStartTime"
                      :allow-clear="false"
                      :placeholder="'请选择'+item.title"
                      :disabled-date="(current)=>{return planStartTimeDisabled(current,row)}"
                      @change="(e)=>{handleComputePeriod(e,row,1)}"
                    />
                    <!-- 计划开始时间 -->
                    <!-- 计划完成时间 -->
                    <a-date-picker
                      v-if="item.dataIndex === 'planEndTime'"
                      v-model="row.planEndTime"
                      :allow-clear="false"
                      :placeholder="'请选择'+item.title"
                      :disabled-date="(current)=>{return planEndTimeDisabled(current,row)}"
                      @change="(e)=>{handleComputePeriod(e,row,2)}"
                    />
                    <!-- 计划完成时间 -->
                    <!-- 完成标准 -->
                    <a-auto-complete
                      v-if="item.dataIndex === 'completeStandard'"
                      v-model="row.completeStandard"
                      :placeholder="'请选择'+item.title"
                      :data-source="completeStandardList"
                      class="width-100"
                      allow-clear
                      :filter-option="true"
                      @change="handleCompleteStandard($event,row)"
                    />
                    <!-- 完成标准 -->
                    <!-- 验证资料 -->
                    <BaseInput
                      v-if="item.dataIndex === 'verifyFiles'"
                      v-model="row.verifyFiles"
                      :placeholder="'请输入'+item.title"
                      @blur="handleUpdate(row)"
                    />
                    <!-- 验证资料 -->
                    <!-- 第一责任人 -->
                    <span
                      v-if="item.dataIndex === 'firstResName'"
                      class="span-btn-ellipsis"
                    >
                      <span
                        v-show="row.firstResName"
                        class="span-btn-ellipsis-text"
                      >
                        {{ row[item.dataIndex] }}
                      </span>
                      <a
                        class="span-btn-ellipsis-btn"
                        @click="handleFirstResNameSelect(row)"
                      > {{ row.firstResName?'(重新选择)':'选择岗位' }} </a>
                    </span>

                    <!-- 第一责任人 -->
                    <!-- 直接责任人 -->
                    <div
                      v-if="item.dataIndex === 'directResPerList'"
                      class="span-btn-ellipsis"
                    >
                      <span
                        v-show="row.directResPerList && row.directResPerList.length>0 && !row.showSelect"
                        class="span-btn-ellipsis-text"
                      >
                        {{ row[item.dataIndex].map(el=>el.label).join(',') }}
                      </span>
                      <a-select
                        v-show="row.showSelect"
                        :ref="'directSelect-' + row.sortNum"
                        v-model="row.directResPerList"
                        :placeholder="'请选择'+item.title"
                        label-in-value
                        mode="multiple"
                        class="span-btn-ellipsis-text"
                        @dropdownVisibleChange="dropdownVisibleChange($event, row)"
                        @change="((value)=>{handleDirectResPerList(value,row)})"
                      >
                        <a-select-option
                          v-for="{employeeId,name,phone} in directlyDutyPersonList"
                          :key="employeeId"
                          :value="employeeId"
                          :data="{directResPerName:name}"
                        >
                          <a-tooltip :placement="'topLeft'">
                            <template slot="title">
                              {{ phone }}
                            </template>
                            {{ name }}
                          </a-tooltip>
                        </a-select-option>
                      </a-select>
                      <a
                        class="span-btn-ellipsis-btn"
                        @click="handleDirectResPerSelect(row,true)"
                      >(点击选择)</a>
                    </div>
                    <!-- 直接责任人 -->
                    <!-- 是否关键线路节点--是否垂直运输设备装拆 -->
                    <a-switch
                      v-else-if="['isKeyNode','isMilestonesNode','isMainProcessNode','isVerticalTransportNode'].includes(item.dataIndex)"
                      v-model="row[item.dataIndex]"
                      checked-children="是"
                      un-checked-children="否"
                      @change="handleUpdate(row)"
                    />
                    <!-- 是否关键线路节点--是否垂直运输设备装拆 -->
                  </template>
                  <template v-else>
                    <!-- 周期(天) -->
                    <BaseInputNumber
                      v-if="item.dataIndex === 'period'"
                      v-model="row.period"
                      :placeholder="'请输入'+item.title"
                      :min="1"
                      :max="2000"
                      :is-int="true"
                      @blur="(e)=>{handleComputePeriod(e.target._value,row,0)}"
                    />
                    <!-- 周期(天) -->
                    <!-- 计划开始时间 -->
                    <a-date-picker
                      v-else-if="item.dataIndex === 'planStartTime'"
                      v-model="row.planStartTime"
                      :allow-clear="false"
                      :placeholder="'请选择'+item.title"
                      :disabled-date="(current)=>{return planStartTimeDisabled(current,row)}"
                      :open="row.planStartTimeOpen"
                      @change="(e)=>{handleComputePeriod(e,row,1)}"
                      @openChange="(e)=>{row.planStartTimeOpen = e}"
                    />
                    <!-- 计划开始时间 -->
                    <!-- 计划完成时间 -->
                    <a-date-picker
                      v-else-if="item.dataIndex === 'planEndTime'"
                      v-model="row.planEndTime"
                      :allow-clear="false"
                      :placeholder="'请选择'+item.title"
                      :disabled-date="(current)=>{return planEndTimeDisabled(current,row)}"
                      :open="row.planEndTimeOpen"
                      @change="(e)=>{handleComputePeriod(e,row,2)}"
                      @openChange="(e)=>{row.planEndTimeOpen = e}"
                    />
                    <!-- 计划完成时间 -->
                    <template v-else-if="item.dataIndex === 'controlLevelId'">
                      {{ row.controlLevelName }}
                    </template>
                    <template v-else-if="item.dataIndex === 'directResPerList'">
                      {{ row[item.dataIndex].map(el=>el.label).join(',') }}
                    </template>
                    <!-- 是否关键线路节点--是否垂直运输设备装拆 -->
                    <a-switch
                      v-else-if="['isKeyNode','isMilestonesNode','isMainProcessNode','isVerticalTransportNode'].includes(item.dataIndex)"
                      v-model="row[item.dataIndex]"
                      checked-children="是"
                      un-checked-children="否"
                      disabled
                    />
                    <!-- 是否关键线路节点--是否垂直运输设备装拆 -->
                    <span
                      v-else
                      class="span-ellipsis"
                    >
                      {{ row[item.dataIndex] }}
                    </span>
                  </template>
                </template>
                <!-- 业务事项 -->
              </span>
              <!-- 编辑 -->
            </template>
          </u-table-column>
        </u-table>
      </a-spin>
    </a-card>
    <div class="page-btn-right-top">
      <a-button
        v-if="!isDetail && !isAudit"
        type="primary"
        :loading="submiting"
        @click="handleSubmit()"
      >
        提交
      </a-button>
      <a-button
        class="ml20"
        @click="$close"
      >
        关闭
      </a-button>
    </div>
    <!-- 选择第一责任人 -->
    <modal
      v-if="firstResNameVisible"
      :id="firstResNameData.id"
      :form-data="firstResNameData.formData"
      :org-query="firstResNameData.orgQuery"
      :screening="true"
      :visible="true"
      @handleCancelFirstRes="firstResNameVisible = false"
      @handleOk="handleFirstResName"
    />
    <!-- 选择第一责任人 -->
    <!-- 选择审批人 -->
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
    <!-- 选择审批人 -->
    <!-- 月/周计划列表筛选查看 -->
    <PlanListFilter
      :visible.sync="planListFilterVisible"
      :data="planListFilterData"
    />
    <!-- 月/周计划列表筛选查看 -->
  </base-breadcrumb>
</template>
<script>
import { UTable, UTableColumn } from 'umy-ui'
import { columns8, controlLevelList, completeStandardList, verifyFilesList } from './model.js'
import constructionSchedule from '@/api/construction/constructionSchedule'
import { plan } from '@/api/construction/constructionSchedule'
import modal from '@/components/SelectJobs'
import { getProjects } from '@/api/construction/planInput'
import PlanListFilter from './components/PlanListFilter'
export default {
  name: 'PlanDetails' + Date.now(),
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  components: {
    UTable,
    UTableColumn,
    modal,
    PlanListFilter
  },
  data() {
    return {
      // 面包屑名字
      breadcrumb: '',
      // 面包屑文字
      breadcrumbText: {
        month: '月',
        week: '周'
      },
      // 计划类型
      mode: this.isAudit ? (this.$route.query.businessType + '' === '103' ? 'month' : 'week') : this.$route.query.mode,
      // 表头
      columns8,
      // 选中项
      selectRow: {},
      // 表格加载
      loading: false,
      // 表格数据
      tableData: [],
      // 统计
      total: {
        projectName: void 0,
        currentProceedPlan: void 0,
        currentProceedNodeNum: void 0,
        currentPlanStartNodeNum: void 0,
        currentPlanEndNodeNum: void 0,
        delayCurrentNodeNum: void 0
      },
      // 管控级别
      controlLevelList,
      // 完成标准
      completeStandardList,
      // 验证资料
      verifyFilesList,
      // 第一责任人模态框显示隐藏
      firstResNameVisible: false,
      // 第一责任人模态框数据
      firstResNameData: {
        id: '',
        formData: {
          fileList: []
        },
        orgQuery: {},
        row: {}
      },
      // 直接责任人列表
      directlyDutyPersonList: [],
      // 项目id
      projectId: this.isAudit ? this.$route.query.businessId + '' : this.$route.query.projectId + '',
      // 提交
      submiting: false,
      // 红灯
      redLight: require('@/assets/icons/redLight.png'),
      // 黄灯
      yellowLight: require('@/assets/icons/yellowLight.png'),
      // 流程配置
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      // 业务id
      businessId: null,
      // 月/周计划列表筛选隐藏显示
      planListFilterVisible: false,
      // 月/周计划列表筛选数据
      planListFilterData: {
        title: '',
        key: '',
        mode: ''
      }
    }
  },
  computed: {
    // 没有选中
    notSelectRow() {
      return JSON.stringify(this.selectRow) === '{}'
    },
    // 是查看
    isDetail() {
      return this.$route.query.pageType === 'detail' || this.isAudit
    }
  },
  watch: {
    // 第一责任人模态框关闭
    predecessorTaskVisible: {
      handler(newV, oldV) {
        if (!newV) {
          this.loadData()
        }
      }
    },
    // 表格数据监听
    tableData: {
      handler(list) {
        if (this.$refs.table) {
          const eachTree = (list) =>{
            for (let i = 0; i < list.length; i++) {
              // 初始化时间弹层隐藏显示(解决时间输入识别后不能自动关闭)
              list[i].planStartTimeOpen = false
              list[i].planEndTimeOpen = false
              if (list[i].childTree) {
                eachTree(list[i].childTree)
              }
            }
          }
          eachTree(this.tableData)
          // 获取之前展开数据
          const expandRecords = this.$refs.table.getTreeExpandRecords()
          // 获取之前滚动高度(表格实例上的scrollTop属性，在滚动到底部时会小于真实的scrollTop值，因此直接从dom获取真实滚动高度)
          const scrollTop = this.$refs.table.tableExample().bodyWrapper.scrollTop
          const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
          // 加载数据
          this.$refs.table.reloadData(list).then(() => {
            // 数据加载完成出现之后，打开之前的展开行
            expandRecords.forEach((row) => {
              this.$refs.table.setTreeExpansion(row, true)
            })
            // 还原之前滚动高度
            this.$refs.table.pagingScrollTopLeft(scrollTop + 1, scrollLeft)
            this.$nextTick(()=>{
              // 不加这一步，列表操作栏 会变形
              this.$refs.table.pagingScrollTopLeft(scrollTop, scrollLeft)
            })
          })
        }
      }
    }
  },
  async created() {
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn(this.mode === 'week' ? 'construction_implementation_week' : 'construction_implementation_month')
  },
  mounted() {
    const text = {
      detail: '详情',
      update: '编辑'
    }
    this.breadcrumb = `施工进度${this.breadcrumbText[this.mode]}计划${text[this.$route.query.pageType]}`
    this.loadData()
    // 获取前置数据
    this.getProjects(this.projectId)
  },
  methods: {
    /**
     * @description: 获取项目部信息
     * @param {string} id 项目id
     * @return {void}
     */
    getProjects(id) {
      getProjects({ projectIds: [id] }).then((res) => {
        this.firstResNameData.orgQuery.ids = res.data[0]?.orgId
      })
    },
    /**
     * @description: 表格数据加载方法
     * @param {boolean} isloading 是否显示加载
     * @return {Promise} 接口Promise
     */
    async loadData(isloading = true) {
      try {
        if (isloading) {
          this.loading = true
        }
        const fun = this.mode === 'week' ? plan.weekPlanDetail : plan.monthPlanDetail
        const {
          code,
          data: { projectName, currentProceedPlan, currentProceedNodeNum, currentPlanStartNodeNum, currentPlanEndNodeNum, delayCurrentNodeNum, treeListVO }
        } = await fun(this.$route.query.id)
        if (code === 200) {
          this.total = {
            projectName,
            currentProceedPlan,
            currentProceedNodeNum,
            currentPlanStartNodeNum,
            currentPlanEndNodeNum,
            delayCurrentNodeNum
          }
          this.tableData = treeListVO
        } else {
          this.tableData = []
        }
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      } finally {
        if (isloading) {
          this.loading = false
        }
      }
    },
    /**
     * @description: 表格行点击
     * @param {object} row 行数据
     * @param {object} column 表头对象
     * @param {event} event 事件对象
     * @return {void}
     */
    handleRowClick(row, column, event) {
      if (this.selectRow?.id !== row.id) {
        this.$set(this, 'selectRow', row)
        // 业务事项
        if (row.nodeType === 1) {
          this.getDirectlyDutyPerson(row)
        }
      }
    },
    /**
     * @description: 获取直接责任人
     * @param {object} row 行数据
     * @return {void}
     */
    getDirectlyDutyPerson(row) {
      constructionSchedule.directlyDutyPersonSelectQuery({ nodeId: row.id, projectId: this.projectId }).then(({ code, data }) => {
        if (code === 200) {
          this.directlyDutyPersonList = data
        } else {
          this.directlyDutyPersonList = []
        }
      })
    },
    /**
     * @description: 格式化时间
     * @param {object/string} date 时间对象或字符串
     * @return {object} moment时间格式
     */
    formatDate(date, toMoment = true) {
      if (date?._isAMomentObject) {
        return toMoment ? date : date.format('YYYY-MM-DD')
      } else {
        return toMoment ? this.moment(date) : date
      }
    },
    /**
     * @description: 计划开始时间禁用
     * @param {object} current 当前时间对象
     * @param {object} row 行数据
     * @return {boolean}
     */
    planStartTimeDisabled(current, row) {
      return row.planEndTime && current && current > this.formatDate(row.planEndTime).endOf('day')
    },
    /**
     * @description: 计划完成时间禁用
     * @param {object} current 当前时间对象
     * @param {object} row 行数据
     * @return {boolean}
     */
    planEndTimeDisabled(current, row) {
      return row.planStartTime && current && current < this.formatDate(row.planStartTime).startOf('day')
    },
    /**
     * @description: 计算周期
     * @param {object} row 行数据
     * @param {number} index 字段索引
     * @return {void}
     */
    handleComputePeriod(value, row, index) {
      if ((value ?? '') === '') {
        this.handleUpdate(row, true)
      } else {
        const { period, planStartTime, planEndTime } = row
        // 长度不在有三个(取消周期)
        const length = [planStartTime, planEndTime].filter((el) => el ?? '' !== '').length
        // 时间周期值个等于2
        if (length === 2) {
          // 修改周期
          if (index === 0) {
            if ((period ?? '') !== '') {
              if ((planStartTime ?? '') !== '') {
                // 计算计划完成时间(三期:计划完成时间 = 计划开始时间 + (周期 - 1))
                row.planEndTime = this.formatDate(planStartTime)
                  .clone()
                  .add(period - 1, 'days')
              } else {
                // 计算计划开始时间(三期:计划开始时间 = 计划完成时间 - (周期 - 1))
                row.planStartTime = this.formatDate(planEndTime)
                  .clone()
                  .subtract(period + 1, 'days')
              }
            }
          }
          // 修改计划开始时间
          if (index === 1) {
            if ((planStartTime ?? '') !== '') {
              if ((planEndTime ?? '') !== '') {
                // 计算周期(三期:周期=(计划完成时间-计划开始时间) + 1)
                row.period = this.formatDate(planEndTime).diff(this.formatDate(planStartTime), 'days') + 1 || void 0
              } else {
                // 计算计划完成时间(三期:计划完成时间 = 计划开始时间 + (周期 - 1))
                row.planEndTime = this.formatDate(planStartTime)
                  .clone()
                  .add(period - 1, 'days')
              }
            }
          }
          // 修改计划完成时间
          if (index === 2) {
            if ((planEndTime ?? '') !== '') {
              if ((planStartTime ?? '') !== '') {
                if(this.moment(planEndTime) < this.moment(row.planStartTime).startOf('day')){
                  this.$message.warning('计划完成时间不能早于计划开始时间')
                }else{
                  // 计算周期(三期:周期=(计划完成时间-计划开始时间) + 1)
                  row.period = this.formatDate(planEndTime).diff(this.formatDate(planStartTime), 'days') + 1 || void 0
                }
              } else {
                // 计算计划开始时间(三期:计划开始时间 = 计划完成时间 - (周期 - 1))
                row.planStartTime = this.formatDate(planEndTime)
                  .clone()
                  .subtract(period + 1, 'days')
              }
            }
          }
        }
        // 时间周期值个等于3
        if (length === 3) {
          // 修改周期或者修改计划开始时间
          if (index === 0 || index === 1) {
            // 计算计划完成时间(三期:计划完成时间 = 计划开始时间 + (周期 - 1))
            row.planEndTime = this.formatDate(planStartTime)
              .clone()
              .add(period - 1, 'days')
          }
          // 修改计划完成时间
          if (index === 2) {
            // 计算周期(三期:周期=(计划完成时间-计划开始时间) + 1)
            row.period = this.formatDate(planEndTime).diff(this.formatDate(planStartTime), 'days') + 1 || void 0
          }
        }
        // 结合open、openChange解决时间选择器不能在输入后自动关闭的问题
        if(index === 1 || index === 2){
          row.planStartTimeOpen = false
          row.planEndTimeOpen = false
        }
        this.handleUpdate(row, true)
      }
    },
    /**
     * @description: 完成标准带出验证资料
     * @param {string} value 完成标准值
     * @param {object} row 行数据
     * @return {void}
     */
    handleCompleteStandard(value, row) {
      const index = this.completeStandardList.findIndex((el) => el === value)
      if (index >= 0) {
        row.verifyFiles = this.verifyFilesList[index]
      }
      this.handleUpdate(row)
    },
    /**
     * @description: 选择第一责任人
     * @param {object} row 当前行数据
     * @return {void}
     */
    handleFirstResNameSelect(row) {
      this.firstResNameData.row = row
      this.firstResNameVisible = true
    },
    /**
     * @description: 选择第一责任人回调
     * @param {object} value 选中项数据
     * @return {void}
     */
    handleFirstResName(value) {
      this.firstResNameData.row.firstResId = value.jobsSelectedId
      this.firstResNameData.row.firstResName = value.jobsSelectedName
      this.firstResNameVisible = false
      this.handleUpdate(this.firstResNameData.row)
    },
    /**
     * @description: 直接责任人下拉展开收起
     * @param {*} visible
     * @param {*} row
     * @return {*}
     */
    dropdownVisibleChange(visible, row) {
      if (!visible) {
        this.handleDirectResPerSelect(row, false)
      }
    },
    /**
     * @description: 直接责任人改变
     * @param {object} value 选中项
     * @param {object} row 行数据
     * @return {void}
     */
    handleDirectResPerList(value, row) {
      row.directResPerList = this.directlyDutyPersonList.filter(item=>value.map(el=>el.key).includes(item.employeeId)).map(el=>{
        return {
          key: el.employeeId,
          label: el.name
        }
      })
      this.handleUpdate(row)
    },
    /**
     * @description: 直接责任人选择
     * @param {object} row 行数据
     * @return {void}
     */
    handleDirectResPerSelect(row, isShow) {
      this.$set(row, 'showSelect', isShow)
      if (row.showSelect) {
        this.$refs[`directSelect-${row.sortNum}`][0].$el.click()
      }
    },
    /**
     * @description: 新增同级节点
     * @param {void}
     * @return {void}
     */
    handleCreateWork() {
      const vm = this
      this.$confirm({
        okText: '确定',
        cancelText: '取消',
        title: '确定新增同级节点吗？',
        onOk() {
          const fun = vm.mode === 'week' ? plan.scheduleWeekSiblingWork : plan.scheduleMonthSiblingWork
          fun({ selectedWorkId: vm.selectRow.id }).then(({ code }) => {
            if (code === 200) {
              vm.$message.success('新增成功')
              vm.loadData()
            }
          })
        }
      })
    },
    /**
     * @description: 删除节点
     * @param {void}
     * @return {void}
     */
    handleRemove() {
      const vm = this
      // 删除业务事项
      this.$confirm({
        okText: '确定',
        cancelText: '取消',
        title: '确定删除新增节点吗？',
        onOk() {
          const fun = vm.mode === 'week' ? plan.scheduleWeekRemoveWork : plan.scheduleMonthRemoveWork
          fun({ selectedWorkId: vm.selectRow.id }).then(({ code }) => {
            if (code === 200) {
              vm.$message.success('删除成功')
              vm.loadData()
            }
          })
        }
      })
    },
    /**
     * @description: 前移一天
     * @param {void}
     * @return {void}
     */
    handlePrepose() {
      const { planStartTime, planEndTime } = this.selectRow
      if ((planStartTime ?? '') !== '' && (planEndTime ?? '') !== '') {
        this.selectRow.planStartTime = this.moment(this.selectRow.planStartTime).subtract('day', 1)
        this.selectRow.planEndTime = this.moment(this.selectRow.planEndTime).subtract('day', 1)
        this.handleUpdate(this.selectRow, true)
      } else {
        this.$message.warning('请先选择计划开始时间和计划结束时间')
      }
    },
    /**
     * @description: 编辑
     * @param {object} row 行数据
     * @param {boolean} refresh 需要刷新
     * @return {void}
     */
    async handleUpdate(row, refresh = false) {
      // 编辑业务事项
      const { id, businessMatters: name, parentId: workPackId, controlLevelId, period, planStartTime, planEndTime, completeStandard, verifyFiles, isKeyNode, firstResId, firstResName, directResPerList } = row
      const fun = this.mode === 'week' ? plan.scheduleWeekEditWork : plan.scheduleMonthEditWork
      const { code } = await fun({
        id,
        name,
        workPackId,
        controlLevelId,
        period,
        planStartTime: this.formatDate(planStartTime, false),
        planEndTime: this.formatDate(planEndTime, false),
        completeStandard,
        verifyFiles,
        isKeyNode,
        firstResId,
        firstResName,
        directResPerList
      })
      if (code !== 200) {
        this.$message.warning('编辑失败')
        this.loadData()
      } else {
        // 刷新表格
        if (refresh) {
          this.loadData()
          this.selectRow = {}
        }
      }
    },
    /**
     * @description: 提交
     * @return {void}
     */
    handleSubmit() {
      const vm = this
      this.$confirm({
        title: '提交确认',
        content: '请确认是否要提交？',
        onOk() {
          const { id } = vm.$route.query
          vm.submiting = true
          const fun = vm.mode === 'week' ? plan.weekPlanSubmitApproval : plan.monthPlanSubmitApproval
          const params = vm.mode === 'week' ? { weekPlanId: id + '' } : { monthPlanId: id + '' }
          vm.setProcessConfig = null
          fun(params)
            .then(({ code }) => {
              if (code === 200) {
                vm.businessId = id
                vm.setProcessConfig = vm.processConfig
              }
            })
            .catch((err) => {
              console.log(err)
            })
            .finally(() => {
              vm.submiting = false
            })
        }
      })
    },
    /**
     * @description: 首字母大写
     * @return {string}
     */
    getCapitalize(str) {
      const tmp = str.toLowerCase()
      return tmp.charAt(0).toUpperCase() + tmp.slice(1)
    },
    /**
     * @description: 月/周计划统计筛选列表
     * @param {string} title 模态框标题
     * @param {string} key 筛选字段
     * @return {void}
     */
    handlePlanListFilter(title, key) {
      if(!this.isDetail) return
      this.planListFilterVisible = true
      this.planListFilterData = {
        title,
        key,
        mode: this.mode,
        id: this.$route.query.id
      }
    },
    /**
     * @description: 展开全部
     * @return {void}
     */
    allTreeExpansion(){
      if(!this.isAudit && !this.isDetail){
        this.loadData()
      }
      this.$refs.table.setAllTreeExpansion()
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
@{deep} .plTableBox .el-table td {
  padding: 2px 0;
  height: 40px !important;
}
@{deep} .plTableBox .el-table th {
  padding: 8px 0;
}
.btn-wrapper {
  margin: 0 -5px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  button {
    margin: 5px;
  }
}
.pub-table-select-count {
  > span {
    margin-right: 12px;
  }
}
.width-100 {
  width: 100%;
}
@{deep} .construction-schedule-view-table .el-table td .cell {
  overflow: visible;
}
.span-ellipsis {
  width: 100%;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}
.span-btn-ellipsis {
  width: 100%;
  display: flex;
  justify-content: center;
}
.span-btn-ellipsis-text {
  width: calc(100% - 85px);
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}
.span-btn-ellipsis-btn {
  width: 75px;
  margin-left: 10px;
}
.sort-num {
  display: block;
  color: #fff;
}
.class-0 {
  // background-color: #d1d1d1;
  color: #606266;
}
.class-1 {
  color: #606266;
}
.class-2 {
  background-color: #f85c62;
}
.class-3 {
  background-color: #1dc682;
}
.class-4 {
  background-color: #ffced0;
}
.plan-list-filter{
  cursor: pointer;
}
</style>
